package com.commerce.addressbook.utlis;

import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;


import com.commerce.addressbook.Entity.Contacts;
import com.commerce.addressbook.Entity.DataBean;
import com.commerce.addressbook.GlobalVariable;


import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import static org.litepal.LitePalApplication.getContext;


public class MyContentResolver {

    private ContentResolver resolver;
    private Context context;

    public MyContentResolver(Context context) {
        this.context = context;
        resolver = context.getContentResolver();
    }

    //查询联系人
    public void getContactsData(){
        Contacts contacts = null;
        List<DataBean> dataBeanList =null;
        DataBean dataBean = null;
        //使用ContentResolver查找联系人数据
        Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        Cursor phoneCursor = null;
        List<List<DataBean>> dataBeans=new ArrayList<>();
        //遍历查询结果，找到所需号码
        while (cursor.moveToNext()) {
            contacts=new Contacts();
            //获取联系人ID
            final String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            //获取联系人的名字
            String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            contacts.setIds(contactId);
            contacts.setContacts(contactName);
            // 查看联系人有多少个号码，如果没有号码，返回0
            int phoneCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
            dataBeanList= new ArrayList<>();
            if (phoneCount > 0) {
                // 获得联系人的电话号码列表
                phoneCursor = resolver.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ "= ?",
                        new String[]{String.valueOf(contactId)},
                        null);
                if (phoneCursor.moveToFirst()) {
                    do {
                        dataBean=new DataBean();
                        //遍历所有的联系人下面所有的电话号码
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        dataBean.setIds(contactId);
                        dataBean.setPhone(phoneNumber);
                        dataBean.setaBoolean(false);
                        dataBeanList.add(dataBean);
                        Log.d("TAG", "getContactsData122: " +dataBeanList.size());
                    } while (phoneCursor.moveToNext());
                }
            }
                dataBean=new DataBean();
                dataBean.setIds(contactId);
                dataBean.setaBoolean(false);
                dataBeanList.add(dataBean);
                dataBeans.add(dataBeanList);
                Log.d("TAG", "getContactsData111: " +dataBeanList.size());
            //联系人保存到数据库
            boolean save = contacts.save();
//            联系人更新到数据库
            if(!save){
                Contacts c = LitePal.where("ids = ?", contactId).find(Contacts.class).get(0);
                if(c.getContacts() != contacts.getContacts()){
                c.setContacts(contacts.getContacts());
                c.updateAll("ids = ?",contactId);
                }
            }
        }
        //单例
        GlobalVariable.getGlobalVariable().setDataBeans(dataBeans);
    }

    /**
     * 添加一个联系人
     * @param name 联系人名字
     * @param phoneNumbers 联系人电话
     */
    public void ContactsInsert(String name, List<DataBean> phoneNumbers) {
        ContentValues contentValues = new ContentValues();
        // 首先向RawContacts.CONTENT_URI执行一个空值插入，目的是获取系统返回的rawContactId
        Uri rawContact_uri = getContext().getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
        long rawContactId = ContentUris.parseId(rawContact_uri);
        // 往data表入姓名数据
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
        resolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
        // 往data表入电话数据
        for (DataBean phoneNumber:phoneNumbers) {
        contentValues.clear();
        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);// 内容类型
        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber.getPhone());
        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        resolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
        }
        Toast.makeText(context, "已保存", Toast.LENGTH_SHORT).show();
    }


    /**
     * 更新联系人电话
     * 联系人的所有信息都是保存在data表中，所以要更新联系人，我们只需要根
     * 据RawContactID和MIMETYPE修改data表中的内容。
     * @param ids 电话列表id
     * @param phoneNumbers 要修改的电话
     * @param phoneNumber  修改前的电话
     */
    public void phoneUpdate(String ids, String phoneNumbers,String phoneNumber) {
        //根据名字修改电话号码
        ContentValues contentValues = new ContentValues();
        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumbers);
        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE);
        int update = resolver.update(ContactsContract.Data.CONTENT_URI, contentValues,
                ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=? AND "+ContactsContract.CommonDataKinds.Phone.NUMBER+" =?",
                new String[]{ids, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,phoneNumber});
        Toast.makeText(context, "已经修改"+update+"条", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除联系人电话
     * @param ids  电话id
     * @param phoneNumber  电话
     */
    public void phoneDel(String ids, String phoneNumber) {
        int delete = resolver.delete(ContactsContract.Data.CONTENT_URI,
                ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=? AND "+ContactsContract.CommonDataKinds.Phone.NUMBER+" =?",
                new String[]{ids, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,phoneNumber});
        Toast.makeText(context, "已经删除"+delete+"条", Toast.LENGTH_SHORT).show();
    }


    /**
     * 删除联系人
     *
     * @param ids 联系人 id
     * @param ids Litepal联系人 id
     */
    public void delContacts(String ids ,int idL,Boolean b) {
        LitePal.delete(Contacts.class,idL);
        //我们拿着这个id，去删除RawContacts表中对应的数据，就可以删掉所以数据了
        resolver.delete(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(ids)), null, null);
        if (b){Toast.makeText(context, "已经删除该联系人", Toast.LENGTH_SHORT).show();}
    }

}
